var createError = require("http-errors");
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");
const cors = require("cors");
var JWT = require("./util/JWT");
// const MongoStore = require("connect-mongo");

var indexRouter = require("./routes/index");
var usersRouter = require("./routes/users");
var loginRouter = require("./routes/login");
var uploadRouter = require("./routes/upload");
var moviesRouter = require("./routes/movies");
var menuRouter = require("./routes/menu");

// 引入
// var session = require("express-session");
var app = express();

// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");

app.use(logger("dev")); // 开发日志
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));

app.use(cors());

// 注册session中间件
// app.use(
//   session({
//     name: "yl_system",
//     secret: "aaksdasdlansdlalsdiasdas", // 服务器生成 session 的签名
//     resave: true, // 重新设置session后，会自动重新计算过期时间
//     saveUninitialized: true, //强制将为初始化的 session 存储
//     cookie: {
//       maxAge: 1000 * 60 * 10, // 过期时间 1h
//       secure: false, // 为 true 时候表示只有 https 协议才能访问cookie
//     },
//     rolling: true, //为 true 表示 超时前刷新，cookie 会重新计时； 为 false 表示在超时前刷新多少次，都是按照第一次刷新开始计时。
//     store: MongoStore.create({
//       mongoUrl: "mongodb://127.0.0.1:27017/kerwin_session", // 新创建了一个数据库
//       ttl: 1000 * 60 * 10, // 过期时间 与上面的过期时间保持一致
//     }),
//   })
// );

// 设置中间件，过期校验
app.use((req, res, next) => {
  // 排除login相关的路由和接口
  if (req.url.includes("login")) {
    next();
    return;
  }

  // 写法一：
  const token = req.headers["authorization"]?.split(" ")[1];
  // 写法二：
  // const token = req.headers["authorization"] && req.headers["authorization"].split(" ")[1];
  if (token) {
    const payload = JWT.verify(token);
    if (payload) {
      // 重新计算token过期时间
      const newToken = JWT.generate(
        {
          _id: payload._id,
          username: payload.username,
        },
        "1d"
      );
      res.header("Authorization", newToken);
      next();
    } else {
      res.status(401).send({ errCode: -1, errInfo: "token过期" });
    }
  } else {
    next();
  }
});

app.use("/", indexRouter);
app.use("/api", usersRouter);
app.use("/apiMovie", moviesRouter);
app.use("/menu", menuRouter);
app.use("/login", loginRouter);
app.use("/upload", uploadRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message; // 设置上下文对象
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render("error");
});

module.exports = app;
